<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="65%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row>
        <el-col :span="21">
          <el-form-item label="拓展目标" prop="targetName">
            <el-input v-model="formData.targetName" placeholder="请输入拓展目标" disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-button plain type="primary" @click="openExpandTargetListDialog()"
            >拓展目标导入</el-button
          >
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="受访人" prop="interviewee">
            <el-input v-model="formData.interviewee" placeholder="请输入受访人" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="受访人电话" prop="intervieweePhone">
            <el-input v-model="formData.intervieweePhone" placeholder="请输入受访人电话" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="受访人职位" prop="intervieweePosition">
            <el-input v-model="formData.intervieweePosition" placeholder="请输入受访人职位" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户需求" prop="customerRequire">
            <el-input v-model="formData.customerRequire" placeholder="请输入客户需求" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="切入点" prop="breakthroughPoint">
            <el-select
              v-model="formData.breakthroughPoint"
              multiple
              placeholder="请选择切入点"
              class="w-1/1"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.FOLLOW_UP_BERAKTHROUGH_POINT)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="拓展时间" prop="expandTime">
            <el-date-picker
              v-model="formData.expandTime"
              type="date"
              value-format="x"
              placeholder="选择拓展时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="业务类型" prop="businessType">
            <el-select v-model="formData.businessType" placeholder="请选择业务类型" class="w-1/1">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.BIZ_BUSINESS_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="拓展进度" prop="expandProcess">
            <el-select
              v-model="formData.expandProcess"
              multiple
              collapse-tags
              placeholder="请选择拓展进度"
              class="w-1/1"
              @change="checkOtherExpandProcess"
            >
              <el-option-group
                v-for="group in ExpandProcessOptionsGroup"
                :key="group.label"
                :label="group.label"
              >
                <el-option
                  v-for="item in group.options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-option-group>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="增值业务" prop="valueAddService" v-if="formData.businessType == '2'">
            <el-select
              v-model="formData.valueAddService"
              placeholder="请选择增值业务"
              class="w-1/1"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.BIZ_VALUE_ADD_SERVICE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="其他描述" prop="otherExpandProcess" v-if="otherExpandProcessFlag">
            <el-input v-model="formData.otherExpandProcess" placeholder="请输入其他描述" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="拓展情况" prop="expandSituation">
            <el-input v-model="formData.expandSituation" placeholder="请输入拓展情况" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户类型" prop="customerType">
            <el-select v-model="formData.customerType" placeholder="请选择客户类型">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.FOLLOW_UP_CUSTOMER_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户级别" prop="customerLevel">
            <el-select v-model="formData.customerLevel" placeholder="请选择客户级别">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.CRM_CUSTOMER_LEVEL)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="下次拜访时间" prop="nextTimeVisit">
            <el-date-picker
              v-model="formData.nextTimeVisit"
              type="date"
              value-format="x"
              placeholder="选择下次拜访时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="现场图片" prop="scenePictureUrl">
            <UploadImgs v-model="formData.scenePictureUrl" class="min-w-80px" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="安全评测报告" prop="securityReportUrl">
            <UploadFile v-model="formData.securityReportUrl" class="min-w-80px" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="服务方案附件" prop="serviceSchemeUrl">
            <UploadFile v-model="formData.serviceSchemeUrl" class="min-w-80px" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="4">
          <el-button @click="show" style="margin-bottom: 20px">定位</el-button>
        </el-col>
        <el-col :span="10">
          <el-form-item label="经度" prop="lng">
            <el-input v-model="formData.lng" placeholder="请输入经度" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="纬度" prop="lat">
            <el-input v-model="formData.lat" placeholder="请输入纬度" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <!-- 百度地图 -->
  <el-dialog
    v-model="openMap"
    title="位置选择"
    width="1000px"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <el-form label-width="80px">
      <el-row>
        <el-col :span="7">
          <el-form-item label="位置经度">
            <el-input size="small" type="text" v-model="addressInfo.longitude" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="位置纬度">
            <el-input size="small" type="text" v-model="addressInfo.latitude" readonly />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="baidu" ref="mapRef" id="baidumap" style="width: 100%; height: 450px"></div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirmSelect"> 确 定 </el-button>
      </span>
    </template>
  </el-dialog>

  <ExpandTargetListDialog ref="expandTargetListDialogRef" @success="setTargetInfo" />
</template>
<script setup lang="ts">
import { ExpandRecordApi, ExpandRecord, ExpandProcessOptionsGroup } from '@/api/biz/expand/record'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'

import { BMPGL } from '@/utils/loadBaiduMap'
import { onMounted, watch, ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import ExpandTargetListDialog from './ExpandTargetListDialog.vue'

/** 拓展记录 表单 */
defineOptions({ name: 'ExpandRecordForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  interviewee: undefined,
  intervieweePhone: undefined,
  intervieweePosition: undefined,
  customerRequire: undefined,
  breakthroughPoint: undefined,
  expandTime: undefined,
  businessType: undefined,
  expandProcess: undefined,
  expandSituation: undefined,
  customerType: undefined,
  customerLevel: undefined,
  nextTimeVisit: undefined,
  scenePictureUrl: undefined,
  securityReportUrl: undefined,
  serviceSchemeUrl: undefined,
  ownerUserId: undefined,
  lng: undefined,
  lat: undefined,
  targetId: undefined,
  targetName: undefined,
  targetType: undefined
})

const formRules = reactive({})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ExpandRecordApi.getExpandRecord(id)
      checkOtherExpandProcess()
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 添加/修改操作 */
const expandTargetListDialogRef = ref()
const openExpandTargetListDialog = (id?: number) => {
  expandTargetListDialogRef.value.open(id)
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ExpandRecord
    console.log(data)
    if (formType.value === 'create') {
      await ExpandRecordApi.createExpandRecord(data)
      message.success(t('common.createSuccess'))
    } else {
      await ExpandRecordApi.updateExpandRecord(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    interviewee: undefined,
    intervieweePhone: undefined,
    intervieweePosition: undefined,
    customerRequire: undefined,
    breakthroughPoint: undefined,
    expandTime: undefined,
    businessType: undefined,
    expandProcess: undefined,
    expandSituation: undefined,
    customerType: undefined,
    customerLevel: undefined,
    nextTimeVisit: undefined,
    scenePictureUrl: undefined,
    securityReportUrl: undefined,
    serviceSchemeUrl: undefined,
    ownerUserId: undefined,
    lng: undefined,
    lat: undefined,
    targetId: undefined,
    targetName: undefined,
    targetType: undefined
  }
  formRef.value?.resetFields()
}

// 地图相关
let map = ref(null)
const mapZoom = ref(15)
const ak = ref('tEpeS8qwvQwKinQkMa7x037oI0jMYFpD')
let openMap = ref(false)
let addressInfo = reactive({
  // 地址信息
  longitude: '', // 经度
  latitude: '' // 纬度
})
watch(
  () => [openMap],
  () => {
    if (!openMap.value) {
      map.value && map.value.destroy()
    }
  },
  { deep: true }
)

const initMap = () => {
  map.value = null
  BMPGL(ak.value).then((BMapGL: any) => {
    map.value = new BMapGL.Map('baidumap')
    var zoomCtrl = new BMapGL.ZoomControl() // 添加缩放控件
    map.value.addControl(zoomCtrl)
    var cityCtrl = new BMapGL.CityListControl() // 添加城市列表控件
    map.value.addControl(cityCtrl)
    var LocationControl = new BMapGL.LocationControl() // 添加定位控件，用于获取定位
    map.value.addControl(LocationControl)
    var scaleCtrl = new BMapGL.ScaleControl() // 添加比例尺控件
    map.value.addControl(scaleCtrl)
    map.value.setMapType() // 设置地图类型为标准地图模式；
    var localcity = new BMapGL.LocalCity()
    localcity.get((e: { name: any }) => {
      map.value.centerAndZoom(e.name, mapZoom.value)
    })

    setTimeout(() => {
      map.value.centerAndZoom(new BMapGL.Point(123.44138, 41.81066), mapZoom.value)
    }, 1000)

    map.value.enableScrollWheelZoom(true)
    map.value.setHeading(64.5)
    map.value.setTilt(73)

    //点击下拉框的值
    map.value.addEventListener('click', function (e: { latlng: { lng: string; lat: string } }) {
      map.value.clearOverlays()
      var point1 = new BMapGL.Point(e.latlng.lng, e.latlng.lat)
      // 创建点标记
      var marker1 = new BMapGL.Marker(point1)
      // 在地图上添加点标记
      map.value.addOverlay(marker1)
      addressInfo.longitude = e.latlng.lng
      addressInfo.latitude = e.latlng.lat
    })
  })
}

/** 打开地图选择 */
const show = () => {
  openMap.value = true
  initMap()
}
/**
 * 确认选择
 */
const confirmSelect = () => {
  formData.value.lng = addressInfo.longitude
  formData.value.lat = addressInfo.latitude
  openMap.value = false
}
/**
 * 取消选择
 */
const cancel = () => {
  openMap.value = false
}

const setTargetInfo = (targetData) => {
  formData.value.targetId = targetData.id
  formData.value.targetName = targetData.name
  formData.value.interviewee = targetData.directorName
  formData.value.intervieweePhone = targetData.contactNumber
  formData.value.targetType = targetData.type
}

const otherExpandProcessFlag = ref(false)
const checkOtherExpandProcess = () => {
  otherExpandProcessFlag.value = false
  if (formData.value.expandProcess != undefined) {
    formData.value.expandProcess.forEach((element) => {
      if (element == '04_03') {
        otherExpandProcessFlag.value = true
      }
    })
  }
}
</script>

<style>
.BMap_cpyCtrl,
.anchorBL {
  display: none;
}
</style>
